package pe.gob.mtpe.renoccsys.utils;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.primefaces.context.RequestContext;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;


public class FacesUtils {

	public static Object getSessionAttribute(String attribute) {
		ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
		HttpSession session = (HttpSession) externalContext.getSession(false);
		Object o = null;
		if (session!=null) {
			o = session.getAttribute(attribute);
		}
		System.out.println("obtenido de session: " + attribute);
		return o;
	}
	
	public static void setSessionAttribute(String attribute, Object value) {
		ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
		HttpSession session = (HttpSession) externalContext.getSession(false);
		session.setAttribute(attribute, value);
		System.out.println("puesto en session: " + attribute);
	}
	
	public static void removeSessionAttribute(String attribute) {
		ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
		HttpSession session = (HttpSession) externalContext.getSession(false);
		session.removeAttribute(attribute);
		System.out.println("removido de session: " + attribute);
	}
	
	/*public static Usuario getUsuarioLogueado() {
		return (Usuario) getSessionAttribute("PGP_Usuario");
	}
	
	public static void setUsuarioLogueado(Usuario usuario) {
		setSessionAttribute("PGP_Usuario", usuario);
	}
	
	public static void removeUsuarioLogueado() {
		removeSessionAttribute("PGP_Usuario");
	}
	
	public static boolean existeUsuarioLogueado() {
		if (getUsuarioLogueado()!=null) {
			return true;
		} else {
			return false;
		}
	}*/
	
	public static void showFacesMessage(String texto, int tipo) {
		switch (tipo) {
		case 1:
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, texto, "Error"));
			break;
		case 2:
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, texto, "Fatal"));
			break;
		case 3:
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, texto, "Informacion"));
			break;
		case 4:
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, texto, "Advertencia"));
			break;
		default:
			break;
		}
	}
	
	 public static void refrescante() {
		    FacesContext context = FacesContext.getCurrentInstance();
		    Application application = context.getApplication();
		    ViewHandler viewHandler = application.getViewHandler();
		    UIViewRoot viewRoot = viewHandler.createView(context, context
		     .getViewRoot().getViewId());
		    context.setViewRoot(viewRoot);
		    context.renderResponse(); 
		  }
	 
	 public static void mostrarReporte(Map parameters,String reporte,List lista, String nombreReporte) throws  JRException,IOException{
	    	
	   	 byte[] bytes=null;
	   	 	 parameters.put("PV_RUTA_IMAGEN",FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/images/logos/logo_mtpe.png")) ;
	   	 	 parameters.put("PV_RUTA_IMAGEN2",FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/images/logos/logo_mtpe2.png")) ;
	   	 	 
	         System.out.println(" 1 ======>"+reporte);
	         ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
	         System.out.println(" 2 ======>");
	        
	         System.out.println(servletContext.getRealPath("/jsfDocs/modulos/reporte/"+reporte));
	         JasperDesign jasperDesign = JRXmlLoader.load(servletContext.getRealPath("/jsfDocs/modulos/reporte/"+reporte));
	         System.out.println(" 3 ======>");
	         JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
	         System.out.println(" 4 ======>");
	         bytes = JasperRunManager.runReportToPdf(jasperReport,parameters, new JRBeanCollectionDataSource(lista));
	         JasperPrint jasperPrint=JasperFillManager.fillReport(jasperReport,parameters, new JRBeanCollectionDataSource(lista));
	         
	         HttpServletResponse response=(HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
	         
	         response.setHeader("Content-Disposition", "inline; filename=\""+nombreReporte+".pdf\";");
	         
	         ServletOutputStream ouputStream = response.getOutputStream();
	         
	         FacesContext facesContext = FacesContext.getCurrentInstance();
	          try {
	        	  System.out.println(" 5 ======>");
	        	 
	             
	              if(bytes != null && bytes.length > 0){
	            	
	                    JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream);
	                   
	                    ouputStream.flush();
	                    ouputStream.close();
	               	  
	                    facesContext.responseComplete();
	                    facesContext.renderResponse();
	                    System.out.println(" 6 ======>");
	                    
	            }
	              
	              
	              
	              
	              
	              System.out.println(" 7 ======>");
	         } catch (Exception e) {
	            
	            e.printStackTrace();
	         }finally{
	        	 
	         }
	          
	  }
	 
	 
	 public static String getIpAddress(){
		 HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		 String ip = "";
		 ip = request.getRemoteAddr();  
		 return ip;
	 }
	 
	 private boolean compararFechas(String fecha1, String fechaActual) {  
		  
		  String resultado="";
		  boolean compara = false;
		  try {
		   /**Obtenemos las fechas enviadas en el formato a comparar*/
		   SimpleDateFormat formateador = new SimpleDateFormat("dd/MM/yyyy"); 
		   Date fechaDate1 = formateador.parse(fecha1);
		   Date fechaDate2 = formateador.parse(fechaActual);
		  
		    if ( fechaDate1.before(fechaDate2) ){
		    resultado= "La Fecha 1 es menor ";
		    compara = true;
		    }else{
		     if ( fechaDate2.before(fechaDate1) ){
		      resultado= "La Fecha 1 es Mayor ";
		      compara = false;
		     }else{
		      resultado= "Las Fechas Son iguales ";
		      compara = true;
		     } 
		    }
		  } catch (Exception e) {
			  	e.printStackTrace();
		  } 
		  System.out.println("resultado de comparacion: " + resultado);
		  return compara;
		 }
	 
	 public static void removeUsuarioLogueado() {
			removeSessionAttribute("muestraLog");
		}
	 
}
